package net.wanho.zx.zx_cms.service;

import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import net.wanho.zx.pojo.cms.CmsPage;
import net.wanho.zx.pojo.cms.CmsTemplate;
import net.wanho.zx.zx_cms.dao.CmsConfigDao;
import net.wanho.zx.zx_cms.dao.CmsPageDao;
import net.wanho.zx.zx_cms.dao.CmsTemplateDao;
import org.apache.commons.io.IOUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.jms.Topic;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author： Depeng.Xu
 * @date： 2020/10/26 16:48
 * @description： TODO
 * @version: 1.0
 */
@Service
public class CmsPageService {

    @Autowired
    private CmsPageDao cmsPageDao;
    @Resource
    GridFsTemplate gridFsTemplate;
    @Resource
    GridFSBucket gridFSBucket;
    @Autowired
    private CmsConfigDao cmsConfigDao;
    @Autowired
    private CmsTemplateDao cmsTemplateDao;
    @Resource
    private Topic topic;
    @Resource
    private JmsMessagingTemplate jmsMessagingTemplate;
    @Resource
    private RestTemplate restTemplate;



    public Page<CmsPage> queryCmsPage(int pagenum, int pagesize, String siteId) {

        ExampleMatcher exampleMatcher = ExampleMatcher.matching().withMatcher("siteId",
                ExampleMatcher.GenericPropertyMatchers.contains()).withIgnorePaths("_class");

        CmsPage cmsPage = new CmsPage();
        cmsPage.setSiteId(siteId);

        Example<CmsPage> example = Example.of(cmsPage,exampleMatcher);

        PageRequest pageRequest = PageRequest.of(pagenum-1,pagesize);
        Page<CmsPage> cmsPages = cmsPageDao.findAll(example,pageRequest);
        return cmsPages;

    }




    public void add(CmsPage cmsPage) {

        cmsPageDao.insert(cmsPage);
    }

    public void deleteCmsPageById(String id) {
        cmsPageDao.deleteById(id);
    }

    public CmsPage queryCmsPageById(String id) {
        Optional<CmsPage> cmsPageOptional = cmsPageDao.findById(id);
        return cmsPageOptional.get();
    }

    public void updateCmsPage(CmsPage cmsPage) {
        cmsPageDao.save(cmsPage);
    }


    public String getTemplateValue(String fileId) throws IOException {

        //根据id查询文件
        GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(fileId)));
        //打开下载流对象
        GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
        //创建gridFsResource，用于获取流对象
        GridFsResource gridFsResource = new GridFsResource(gridFSFile, gridFSDownloadStream);
        //获取流中的数据
        String s = IOUtils.toString(gridFsResource.getInputStream(), "UTF-8");
        return s;
    }

    public void generateHtml(String pageId) throws IOException, TemplateException {
        CmsPage cmsPage = cmsPageDao.findById(pageId).get();
        Map map = this.getDataFromUrl(cmsPage.getDataUrl());
        //拿模板
        CmsTemplate cmsTemplate = cmsTemplateDao.findById(cmsPage.getTemplateId()).get();
        String templateValue = getTemplateValue(cmsTemplate.getTemplateFileId());
        Template template = new Template("template", new StringReader(templateValue), new Configuration(Configuration.VERSION_2_3_23));
        //拿地址
        String path = cmsPage.getPagePhysicalPath()+"/"+cmsPage.getPageWebPath();
        /*new FileWriter(new File(path))*/
        template.process(map,new FileWriter(new File(cmsPage.getPagePhysicalPath())));

    }

    public void preview(String pageId, HttpServletResponse response) throws IOException, TemplateException {
        CmsPage cmsPage = cmsPageDao.findById(pageId).get();
        Map map = this.getDataFromUrl(cmsPage.getDataUrl());
        //拿模板
        CmsTemplate cmsTemplate = cmsTemplateDao.findById(cmsPage.getTemplateId()).get();
        String templateValue = getTemplateValue(cmsTemplate.getTemplateFileId());
        Template template = new Template("template", new StringReader(templateValue), new Configuration(Configuration.VERSION_2_3_23));
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=utf-8");
        template.process(map,response.getWriter());

    }

    public Map getDataFromUrl(String dataurl){
        ResponseEntity<Map> forEntity = restTemplate.getForEntity(dataurl, Map.class);
        Map map = forEntity.getBody();
        return map;
    }

    public void upload2Gridfs(String pageId) throws IOException, TemplateException {

        CmsPage cmsPage = cmsPageDao.findById(pageId).get();
        String path = cmsPage.getPagePhysicalPath();

        //要存储的文件
        File file = new File(path);
        //定义输入流
        FileInputStream fileInputStream = new FileInputStream(file);
        //向GridFS存储文件
        ObjectId objectId = gridFsTemplate.store(fileInputStream, "index.html", "text");
        //得到文件id
        String fileId = objectId.toString();
        //设置cmsPage的htmlFileId属性,
        cmsPage.setHtmlFileId(fileId);
        cmsPageDao.save(cmsPage);
        jmsMessagingTemplate.convertAndSend(topic,pageId);
    }
}

